/*
 * @lc app=leetcode.cn id=56 lang=golang
 *
 * [56] 合并区间
 */

// @lc code=start
func merge(intervals [][]int) [][]int {
	sort.SortFunc(intervals, func(p, q []int) int {
		return p[0] - q[0]
	})

	ans := [][]int{}
	pre := []int{intervals[0][0], intervals[0][1]}
	for i := 1; i < len(intervals); i++ {
		cur := intervals[i]

		if pre[1] >= cur[0] {
			pre[0] = pre[0]
			pre[1] = max(pre[1], cur[1])
		} else {
			ans = append(ans, []int{pre[0], pre[1]})
			pre[0] = cur[0]
			pre[1] = cur[1]
		}
	}
	ans = append(ans, []int{pre[0], pre[1]})
	return ans
}

// @lc code=end

